﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;

public partial class Default2 : System.Web.UI.Page
{
    List<string> fields = new List<string>();
    ArrayList values = new ArrayList();
    List<string> types = new List<string>();
    /////////////////////////////////////
    List<string> fields2 = new List<string>();
    ArrayList values2 = new ArrayList();
    List<string> types2 = new List<string>();
    /////////////////////////////////////
    string auther = "";
    string title = "";
    string desc = "";
    string topic = "";
    string pups = "";
    string issn = "";
    string dwoy = "";
    string lc = "";
    /// <summary>
    /// /
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("ar-SA");
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("ar-SA");
        } 
      
  
    }

    public void form1Mrc(string[] fs)
    {
     
        
        fields2.Add("tag");
        types2.Add("string");
        values2.Add("000");
        /////////////////////////////////////////////////
       
        fields2.Add("field");
        types2.Add("string");
        values2.Add(fs[0].Substring(5));
        /////////////////////////////////////////////// 
        
        Regex regex = new Regex("^(\\d{3})");
        string tag = "";
        string ind = "";
        string field = "";

       
         foreach (string fx in fs)
            {
             
                string ff = fx.Replace("=", "");
                ff = ff.Replace("\\", "");
                Match  match = regex.Match(ff);
                if (match.Groups[1].Value != "")
                {
                    tag = match.Groups[1].Value;
                    /////////////////////////////////////////

                    fields2.Add("tag");
                    types2.Add("string");
                    values2.Add(tag);
                    
                    /////////////////////////////////////////////////
                   

                    /////////////////////////////
                    ff = ff.TrimStart(tag.ToCharArray());
                    ff = ff.TrimStart();
                    if (ff.Contains("$"))
                    {
                        string[] mm = ff.Split("$".ToCharArray());
                        if (mm[0] != "")
                        {
                            ind = mm[0];
                            //////////////////////////////
                            fields2.Add("indicator");
                            types2.Add("string");
                            values2.Add(ind);
                            /////////////////////////////////////////////////  

                        }
                         string subs="";
                        for (int i = 1; i< mm.Length;i++)
                        {
                            subs += mm[i].Substring(0, 1)+"$";
                            mm[i] = mm[i].Replace('"', ' ');
                            mm[i] = mm[i].Replace("'", "");
                            mm[i]=  mm[i].Remove(0, 1); 
                            //////////////////////////////
                           
                          
                            field += mm[i] + "%";
                        }
                        fields2.Add("subfield");
                        types2.Add("string");
                        values2.Add(subs.TrimEnd('$'));
                        /////////////////////////////////////////////////  
                        //////////////////////////////
                        fields2.Add("field");
                        types2.Add("string");
                        values2.Add(field.TrimEnd('%'));
                        ///////////////////////////////////////////////  
                        switchs(tag, field.Replace('%',' '));

                    }
                    else
                    {
                        ff = ff.Replace('"', ' ');
                        ff = ff.Replace("'", "");
                        //////////////////////////////
                        fields2.Add("field");
                        types2.Add("string");
                        values2.Add(ff);
                        //////////////////////////
                        switchs(tag, ff);
                        ///////////////////////////////////////////////////     
                        field = ff;
                    }
                    //Response.Write(tag + "   " + ind + "   " + field);
                    //Response.Write("<br />");
                  
                }
                 tag = "";
                 ind = "";
                 field = "";
              

            }
         insertion();
  
    }

    
    public void form2Mrc(string[] fs)
    {
        //List<string> fields2 = new List<string>();
        //ArrayList values2 = new ArrayList();
        //List<string> types2 = new List<string>();
        ///////////////////////////////////////

        Regex regex2 = new Regex("^(\\t \\t\\d|\\t\\d\\t\\d|\\t\\d)");
        Regex regex = new Regex("^(\\d{3})");
        string tag = "";
        string ind = "";
        string field = "";
        ///////////////////////////////////////////
        /////////////////////////////////////
        fields2.Add("tag");
        types2.Add("string");
        values2.Add("000");
        /////////////////////////////////////////////////

        fields2.Add("field");
        types2.Add("string");
        string vv=fs[0].Replace("MARC Leader","");
        values2.Add(vv.Trim());
        /////////////////////////////////////////////// 
          foreach (string fx in fs)
            {
                string ff = fx;
            Match match = regex.Match(ff);
            if (match.Groups[1].Value != "")
            {

                tag = match.Groups[1].Value;
              /////////////////////////////////////
                /////////////////////////////////////////

                fields2.Add("tag");
                types2.Add("string");
                values2.Add(tag);

                /////////////////////////////////////////////////
                ff = ff.TrimStart(tag.ToCharArray());
                
                match = regex2.Match(ff);
                if (match.Groups[1].Value != "")
                {
                    ind = match.Groups[1].Value;

                    ff = ff.TrimStart(ind.ToCharArray());
                    ind = ind.Replace("\t", "");
                    //////////////////////////////
                    fields2.Add("indicator");
                    types2.Add("string");
                    values2.Add(ind);
                    /////////////////////////////////////////////////
                    if (ff.Contains("|"))
                    {
                        string[] mm = ff.Split("|".ToCharArray());

                        string subs = "";
                        field = mm[0];
                        for (int i = 1; i < mm.Length; i++)
                        {
                            subs += mm[i].Substring(0, 1) + "$";
                            mm[i] = mm[i].Replace('"', ' ');
                            mm[i] = mm[i].Replace("'", "");
                            mm[i] = mm[i].Remove(0, 1);
                            //////////////////////////////


                            field += mm[i] + "%";
                        }

                        fields2.Add("subfield");
                        types2.Add("string");
                        values2.Add(subs.TrimEnd('$'));
                        /////////////////////////////////////////////////  
                        //////////////////////////////
                        fields2.Add("field");
                        types2.Add("string");
                        values2.Add(field.TrimEnd('%'));
                        ///////////////////////////////////////////////  
                        switchs(tag, field.Replace('%', ' '));

                    }
                    else
                    {
                        ff = ff.Replace('"', ' ');
                        ff = ff.Replace("'", "");
                        //////////////////////////////
                        //////////////////////////////
                        fields2.Add("field");
                        types2.Add("string");
                        values2.Add(ff);
                        ///////////////////////////////////////////////  
                        switchs(tag, ff);
                        field = ff;
                    }
                }
                else
                {
                    ff = ff.Replace('"', ' ');
                    ff = ff.Replace("'", "");
                    //////////////////////////////
                    //////////////////////////////
                    fields2.Add("field");
                    types2.Add("string");
                    values2.Add(ff);
                    ///////////////////////////////////////////////  
                    switchs(tag, ff);
                    field = ff;
                
                }

            }
           
            //Response.Write(tag + "   " + ind + "   " + field);
            //Response.Write("<br />");

        }
        insertion();

    }
    public void form3Mrc(string fs)
    {

        //List<string> fields2 = new List<string>();
        //ArrayList values2 = new ArrayList();
        //List<string> types2 = new List<string>();
        ///////////////////////////////////////


         FileMARC marcRecords = new FileMARC(fs);
     
        foreach (Record record in marcRecords)
        {
            //Response.Write(record.Leader);
            //Response.Write("<br />");
            fields2.Add("tag");
            types2.Add("string");
            values2.Add("000");
            /////////////////////////////////////////////////

            fields2.Add("field");
            types2.Add("string");
            values2.Add(record.Leader);
            /////////////////////////////////////////////// 
            foreach (Field fld in record.Fields)
            {
                fields2.Add("tag");
                types2.Add("string");
                values2.Add(fld.Tag);
                /////////////////////////////////////////////////

                if (fld.IsDataField())
                {

                    DataField cc = (DataField)fld;
                    string ind = (cc.Indicator1 + cc.Indicator2).ToString();
                    string subs = "";
                    string field = "";
                    foreach (Subfield sub in cc.Subfields)
                    {
                        subs += sub.Code + "$";
                        field += sub.Data + "%";

                    }
                    field = field.Replace('"', ' ');
                    field = field.Replace("'", "");
                    //////////////////////////////
                    fields2.Add("subfield");
                    types2.Add("string");
                    values2.Add(subs.TrimEnd('$'));
                    /////////////////////////////////////////////////  
                    //////////////////////////////
                    fields2.Add("field");
                    types2.Add("string");
                    values2.Add(field.TrimEnd('%'));
                    ///////////////////////////////////////////////  
                    switchs(fld.Tag, field.Replace('%',' '));
                }
                else
                {
                    if (fld.IsControlField())
                    {
                        ControlField cc = (ControlField)fld;
                        //////////////////////////////
                        fields2.Add("field");
                        types2.Add("string");
                        values2.Add(cc.Data);
                        ///////////////////////////////////////////////
                        switchs(fld.Tag, cc.Data);
                    }
                
                }
                /////////////////////////////////////////////// 
           
                //Response.Write(fld.Tag + "    " + fld.FormatField());
                //Response.Write("<br />");
            }
            insertion();
        }
    }
    public void insertion()
    {


        int f = DB.INSERT2("products", fields, types, values);
        if (f > 0)
        {

            //////////////////////////////
            for (int i = 0; i < fields2.Count; i++)
            {
                string inds = "";
                string myfield = "";
                string mytag = "";
                string mysub = "";
                if (fields2[i] == "tag")
                {
                    mytag = (string)values2[i];
                    if (fields2[i + 1] == "indicator")
                    {
                        inds = (string)values2[i + 1];
                        // DB.INSERTag((string)values2[i], inds, f);
                        i++;
                        if (fields2[i + 1] == "subfield")
                        {
                            mysub = (string)values2[i + 1];
                            i++;
                            if (fields2[i + 1] == "field")
                            {
                                myfield = (string)values2[i + 1];
                                i++;
                            }

                        }

                        else
                        {
                            if (fields2[i + 1] == "field")
                            {
                                myfield = (string)values2[i + 1];
                                i++;
                            }

                        }

                    }
                    else
                    {
                        if (fields2[i + 1] == "subfield")
                        {
                            mysub = (string)values2[i + 1];
                            i++;
                            if (fields2[i + 1] == "field")
                            {
                                myfield = (string)values2[i + 1];
                                i++;
                            }

                        }

                        else
                        {
                            if (fields2[i + 1] == "field")
                            {
                                myfield = (string)values2[i + 1];
                                i++;
                            }

                        }

                    }

                    DB.INSERTag(mytag, inds, f, mysub, myfield);
                }
            }
        }

    }
    public void switchs(string tag, string val)
    {



        switch (tag)
        {
            case "100":
                //// / //////auther////////////////////////////
                if (auther == "")
                {
                    fields.Add("auther1");
                    types.Add("string");
                    values.Add(val);
                    auther = val;
                }
                /////////////////////////////////////////////////
                break;
            ////////isbn//////////
            case "020":
                //////////////////
                if (issn == "")
                {

                    fields.Add("issn");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    //////////////////
                    fields.Add("product_type_id");
                    types.Add("int");
                    values.Add(1);
                    ///////////////
                    issn = val;
                }
                break;
            //////issn//////
            case "022":
                //////////////////
                if (issn == "")
                {

                    fields.Add("issn");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    //////////////////
                    fields.Add("product_type_id");
                    types.Add("int");
                    values.Add(2);
                    ///////////////
                    issn = val;
                }
                break;
            //////congress//////
            case "050":
                //////////////////
                if (lc == "")
                {

                    fields.Add("lc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    
                    lc = val;
                }
                break;
            //////dewey//////
            case "082":
                //////////////////
                if (dwoy == "")
                {

                    fields.Add("dwoy");
                    types.Add("string");
                    values.Add(val);
                    ///////////////

                    dwoy = val;
                }
                break;
            case "240":
                ////////title//////////
                if (title == "")
                {
                    fields.Add("product");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    title = val;
                }
                break;
            ///////title///////////
            case "245":
                if (title == "")
                {
                    //////////////////
                    fields.Add("product");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    title = val;
                }
                break;
            ///////title//////////
            case "222":
                if (title == "")
                {
                    //////////////////
                    fields.Add("product");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    title = val;
                }
                break;
            case "650":
                //////////////////
                if (topic == "")
                {
                    fields.Add("topic");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    topic = val;
                }
                break;
            //////desc////////
            case "500":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            /////////desc///////
            case "504":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            /////////desc///////
            case "505":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            /////////desc///////
            case "530":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            /////////desc///////
            case "590":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            case "260":
                if (pups == "")
                {
                    //////////////////
                    fields.Add("publisher");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    pups = val;
                }
                break;
            ////////////////////////
            default:


                break;
        }



    }
    ///////////////////////
    //protected override void InitializeCulture()
    //{
    //    string lang = Request["Language1"];
    //    if (lang != null && lang != "")
    //    {
    //        Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
    //        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
    //    }
    //}
    protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        if (AsyncFileUpload1.HasFile)
        {
            
            string paths = Server.MapPath(Request.ApplicationPath) + "\\" + AsyncFileUpload1.FileName;
            AsyncFileUpload1.SaveAs(paths);
            AsyncFileUpload1.ClearAllFilesFromPersistedStore();


            string[] fs = File.ReadAllLines(paths, System.Text.Encoding.GetEncoding("UTF-8"));


            Regex regex3 = new Regex("^(=*)");
            Regex regex4 = new Regex("(MARC)");

            Match match = regex3.Match(fs[0]);
            if (match.Groups[1].Value != "")
            {
                form1Mrc(fs);

            }
            else
            {
                match = regex4.Match(fs[0]);
                if (match.Groups[1].Value != "")
                {
                    form2Mrc(fs);
                }
                else
                {
                    if (fs.Length == 1)
                    {

                        form3Mrc(fs[0]);
                    }

                }
            }

           
        }
        //GridView1.DataSource = SqlDataSource1;
        //GridView1.DataBind();
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    e.Row.Attributes.Add("onmouseover", "this.Mystyle=this.style.backgroundColor;this.style.backgroundColor='#99CDFF'");

        //    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.Mystyle");
        //}
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "show")
        {

            int  ff =int.Parse((e.CommandArgument).ToString());
          //  MARCDetails1.setMarc(DB.getMarc(ff));
            //ScriptManager.RegisterStartupScript(this.up1, this.GetType(), "hj", "there();", true);
        }
    }


    public void insertfld(string tag,string ins,string flds)
    {
    
     //////////////////////////////
         fields2.Add("tag");
         types2.Add("string");
         values2.Add(tag);
         ///////////////////////////////////////////////
         //////////////////////////////
         fields2.Add("indicator");
         types2.Add("string");
         values2.Add(ins);
         ///////////////////////////////////////////////
         //////////////////////////////
         fields2.Add("field");
         types2.Add("string");
         values2.Add(flds);
        ///////////////////////////////////////////////
         //////////////////////////////
    }


    protected void save_Click(object sender, EventArgs e)
    {
        insertfld("000", "", leader.Text);
        insertfld("008", "", fix.Text);
        //////////////////////////////
        switchs("050", lcs.Text);
        insertfld("050", "", lcs.Text);
        /////////////////////////////////////
        //////////////////////////////
        switchs(DropDownList1.SelectedValue, isn.Text);
        insertfld(DropDownList1.SelectedValue, "", isn.Text);
        /////////////////////////////////////
        switchs("082", dewey.Text);
        insertfld("082", "", dewey.Text);
        ///////////////////////////////////
        switchs("260", pup.Text);
        insertfld("260", "", pup.Text);
        /////////////////////////////
        switchs("100", auth.Text);
        insertfld("100", "", auth.Text);
        //////////////////////////////////////
        insertfld("035", "", f35.Text);
        //////////////////////////////
        switchs("245", address.Text);
        insertfld("245", "", address.Text);
        /////////////////////////////////////////
        insertfld("300", "", f300.Text);
        ////////////////////////////////////////
        /////////////////////////////////////////
        insertfld("310", "", f310.Text);
        ////////////////////////////////////////
        /////////////////////////////////////////
        insertfld("005", "", f005.Text);
        ////////////////////////////////////////
        switchs("650", topics.Text);
        insertfld("650", "", topics.Text);
        //////////////////////////////////////
        switchs("500", notes.Text);
        insertfld("500", "", notes.Text);
        // //////////////////////////////
        //"SELECT [id], [product], [productdesc], [publisher], [topic], [product_type_id], [issn], [dwoy], [lc], [auther1] FROM [products] "
        if (Grid1.AddedItems.Length > 0)
        {
            for (int i = 0; i < Grid1.AddedItems.Length; i++)
            {
                if ((Grid1.AddedItems[i].Cells[3].Value != null) && (Grid1.AddedItems[i].Cells[1].Value != null))
                {
                    string tag = Grid1.AddedItems[i].Cells[3].Value.ToString();
                    string ins = (Grid1.AddedItems[i].Cells[2].Value.ToString() == null ? "" : Grid1.AddedItems[i].Cells[2].Value.ToString());
                    string fd = Grid1.AddedItems[i].Cells[1].Value.ToString();
                    insertfld(tag, ins, fd);
                }
            }
        }
        insertion();



    }

   
    
}
